home *** CD-ROM | disk | FTP | other *** search
- Path: atglab.bls.com!Alun.Champion
- From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
- Newsgroups: comp.lang.c++
- Subject: Re: [] overload..(newbie in distress)
- Date: 23 Jan 1996 15:59:15 GMT
- Organization: Computer People Inc.
- Message-ID: <ALUN.CHAMPION.96Jan23105915@g7240065.bridge.bst.bls.com>
- References: <DLGppJ.31C@undergrad.math.uwaterloo.ca>
- <4e0ui5$kjn@newsroom.hitc.com>
- NNTP-Posting-Host: bstfirewall.bst.bls.com
- In-reply-to: psand@eos.hitc.com's message of 22 Jan 1996 21:11:33 GMT
-
- In article <4e0ui5$kjn@newsroom.hitc.com> psand@eos.hitc.com (G. Patrick Sand) writes:
-
- : In article <DLGppJ.31C@undergrad.math.uwaterloo.ca>,
- : tthiraku@landen.math.uwaterloo.ca says...
- :>
- :> I'm currently stuck on how to overload [] operator such that
- :> it does two different tasks..
- :>
- :> case 1:
- :> // A is an instance of a class that contains a linkist.
- :>
- :> A[5] = val; // store val into the fifth node of a linklist.
- :> val = A[5] ; // returns the value of the fifth node of a linklist.
- :>
- :>
- :> I was wondering how can C++ differentiate these two senerios?
-
- : I think you need the following definitions:
-
- : //(T is the value class name, ARRAY is the array class name)
-
- : const T ARRAY::operator[]( int i ); // for the x = a[5] operation
- : T& ARRAY::operator[]( int i ); // for the a[5] = x operation
-
- Hmm. Close but no cigar ;')
- C++ does not overload on the return type of functions so these two
- to the compiler have the same overloading signature and will complain
- about duplicate declaration of operator [] ...
-
- What I think you meant is for the first one:
-
- T ARRAY::operator[] (int i) const;
-
- The const on the return type is almost useless as it returns this by value
- if instead you had
-
- const T& ARRAY::operator[] (int i) const;
-
- Then the const on the return type is absolutely necessary.
-
- : Haven't tried it but I bet I am on the right track...Of course, I think
- : just defining the second one will work...
-
- You do need the first one in cases when you have a const ARRAY;
-
- Regards
-
- -A.
- --
- | A.Champion |
-